package com.zh.work.controller.platform.menu;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zh.common.annotaion.*;
import com.zh.common.constans.AuthConstant;
import com.zh.common.entity.JSONResult;
import com.zh.common.entity.ElecMenu;
import com.zh.common.entity.Oauth;
import com.zh.work.dao.platform.menu.MenuDaoMapper;
import com.zh.work.service.platform.menu.MenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Date;
import java.util.List;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * @Description: 菜单设置控制器
 * @Author: Li.HuiNeng
 * @Create in: 2019-10-09 10:50
 * @Version: 1.0.1
 */
//@PreAuthorize("hasAuthority('/basic_set/menu_set')")
@Api(value = "MenuController", tags = "菜单管理控制器")
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    @Autowired
    private MenuDaoMapper menuDaoMapper;

    @Autowired
    private RedisTemplate redisTemplate;



//    @PreAuthorize("hasAuthority('/basic_set/menu_set/get')")
    @ApiOperation(value = "分页查询菜单数据集", tags = {"getPagesMenu"}, notes = "分页查询菜单数据集")
    @GetMapping("/getPagesMenu")
    public JSONResult<List<ElecMenu>> getPagesMenu(
            @CurrentUser Principal principal,
            @ApiParam(value = "起始页", name = "pageNo")Integer pageNo,
            @ApiParam(value = "当前页显示数量", name = "pageNo")Integer pageSize,
            @ApiParam(value = "菜单实体类", name = "menu") ElecMenu menu) {
        Oauth auth = (Oauth) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        JSONResult<List<ElecMenu>> jsonResult = new JSONResult<>();
        try {
            Page<ElecMenu> page = new Page<>(pageNo, pageSize);
            IPage<ElecMenu> result = this.menuService.selectPageMenus(page, menu);
            jsonResult.setTotal(page.getTotal());
            jsonResult.setData(result.getRecords());
            jsonResult.setMessage("操作成功");
            jsonResult.setSuccess(true);
            jsonResult.setCode(200);
        } catch (Exception e) {
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setSuccess(false);
            e.printStackTrace();
        }
        return jsonResult;
    }

//    @PreAuthorize("hasAuthority('/basic_set/menu_set/add')")
    @ApiOperation(value = "新增一条记录", tags = {"putElecMenu"}, notes = "新增一条记录")
    @PutMapping("/putElecMenu")
    @ResponseBody
    public JSONResult<Object> putElecMenu(
            @ApiParam(value = "菜单实体类", name = "elecMenu")
            @RequestBody ElecMenu elecMenu) {
        Oauth auth = (Oauth) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        JSONResult<Object> jsonResult = new JSONResult<>();
        elecMenu.setMenuOp(auth.getUserLoginName());
//        elecMenu.setMenuOp(Integer.valueOf(auth.getUserRoleNo()));
        elecMenu.setMenuDate(new Date());
        try {
            if (elecMenu.insert()) {
                this.removeRedisCache();
                jsonResult.setCode(200);
                jsonResult.setMessage("添加完成");
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setMessage("添加失败,请检查参数是否填写完整!");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setCode(e.hashCode());
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
            e.printStackTrace();
        }
        return jsonResult;
    }


//    @PreAuthorize("hasAuthority('/basic_set/menu_set/update')")
    @ApiOperation(value = "通过id修改信息", tags = {"updateElecMenuById"}, notes = "通过id修改信息")
    @PutMapping("/updateElecMenuById")
    @ResponseBody
    public JSONResult<Object> updateElecMenuById(@ApiParam(value = "菜单实体类", name = "elecMenu")
                                                         @RequestBody ElecMenu elecMenu) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        Oauth auth = (Oauth) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        try {
            if (elecMenu.updateById()) {
                this.removeRedisCache();
                jsonResult.setCode(200);
                jsonResult.setMessage("修改完成");
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setMessage("修改失败,请检查参数是否填写完整!");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setCode(e.hashCode());
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setSuccess(false);
            e.printStackTrace();
        }
        return jsonResult;
    }


//    @PreAuthorize("hasAuthority('/basic_set/menu_set/del')")
    @ApiOperation(value = "根据主键删除记录", tags = {"deleteElecMenuById"}, notes = "根据主键删除记录")
    @DeleteMapping("/deleteElecMenuById")
    public JSONResult<Object> deleteElecMenuById(
            @ApiParam(value = "菜单实体类", name = "elecMenu") ElecMenu elecMenu) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        Oauth auth = (Oauth) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        try {
            if (elecMenu.deleteById()) {
                this.removeRedisCache();
                jsonResult.setCode(200);
                jsonResult.setMessage("删除完成");
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setMessage("删除失败,请检查参数是否填写完整!");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setCode(e.hashCode());
            e.printStackTrace();
        }
        return jsonResult;
    }

//    @PreAuthorize("hasAuthority('/basic_set/menu_set/dels')")
    @ApiOperation(value = "根据主键列表批量删除记录", tags = {"deleteElecMenuBatchByIds"}, notes = "该传参时 请选择raw(application/json)格式传入")
    @DeleteMapping("/deleteElecMenuBatchByIds")
    @ResponseBody
    public JSONResult<Object> deleteElecMenuBatchByIds(@ApiParam(value = "主键集合", name = "ids") @RequestBody @RequestParam("ids") List<Integer> ids) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        Oauth auth = (Oauth) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        try {
            int c = this.menuDaoMapper.deleteBatchIds(ids);
            if (c > 0) {
                this.removeRedisCache();
                jsonResult.setCode(200);
                jsonResult.setMessage("删除完成");
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setMessage("删除失败,请检查参数是否填写完整!");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setCode(e.hashCode());
            e.printStackTrace();
        }
        return jsonResult;
    }

    // 清楚缓存内容
    @Async
    void removeRedisCache() {
        redisTemplate.delete(AuthConstant.REDIS_WEB_MENU_KEY);
    }
}
